using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
using System.Windows.Media.Media3D;
using HelixToolkit.Wpf;
using Microsoft.Win32;
using lwd800.Views;
using lwd800.Views.Pages; // 引用你的页面

namespace lwd800.ViewModels
{
    public class MainViewModel : INotifyPropertyChanged
    {
        // 顶部菜单按钮
        public ObservableCollection<TopMenuButton> TopMenuButtons { get; set; }

        // 底部进度条
        public ObservableCollection<StatusProgressBar> StatusProgressBars { get; set; }

        // 监控相关
        private string _monitorIP = "192.168.1.100";

        public string MonitorIP
        {
            get => _monitorIP;
            set
            {
                _monitorIP = value;
                OnPropertyChanged();
            }
        }

        private bool _isMonitorSettingVisible;

        public bool IsMonitorSettingVisible
        {
            get => _isMonitorSettingVisible;
            set
            {
                _isMonitorSettingVisible = value;
                OnPropertyChanged();
            }
        }

        //选中属性
        private int _selectedTopMenuIndex;

        public int SelectedTopMenuIndex
        {
            get => _selectedTopMenuIndex;
            set
            {
                _selectedTopMenuIndex = value;
                OnPropertyChanged();
            }
        }

        // 3D模型相关
        private Model3D _model3D;

        public Model3D Model3D
        {
            get => _model3D;
            set
            {
                _model3D = value;
                OnPropertyChanged();
            }
        }

        private bool _isModelLoaded;

        public bool IsModelLoaded
        {
            get => _isModelLoaded;
            set
            {
                _isModelLoaded = value;
                OnPropertyChanged();
            }
        }

        private string _currentModelFilePath;

        // 时间
        private string _currentTime;

        public string CurrentTime
        {
            get => _currentTime;
            set
            {
                _currentTime = value;
                OnPropertyChanged();
            }
        }

        // 页面切换
        private object _currentPage;

        public object CurrentPage
        {
            get => _currentPage;
            set
            {
                _currentPage = value;
                OnPropertyChanged();
            }
        }

        private DispatcherTimer _timer;

        // 命令
        public ICommand ShowMonitorSettingCommand { get; }
        public ICommand ConnectMonitorCommand { get; }
        public ICommand UploadFileCommand { get; }
        public ICommand DeleteFileCommand { get; }
        public ICommand ShowMenuCommand { get; }
        public ICommand LogoutCommand { get; }

        public MainViewModel()
        {
            // 顶部菜单按钮
            TopMenuButtons = new ObservableCollection<TopMenuButton>
            {
                new TopMenuButton("首页") { Icon = "pack://application:,,,/assets/home.png" },
                new TopMenuButton("手动模式") { Icon = "pack://application:,,,/assets/print.png" },
                new TopMenuButton("参数设置") { Icon = "pack://application:,,,/assets/settings.png" },
                new TopMenuButton("系统设置") { Icon = "pack://application:,,,/assets/error.png" },
                new TopMenuButton("设备监控") { Icon = "pack://application:,,,/assets/camera.png" },
                new TopMenuButton("文件管理") { Icon = "pack://application:,,,/assets/document.png" },
            };

            // 底部状态栏进度条
            StatusProgressBars = new ObservableCollection<StatusProgressBar>
            {
                new StatusProgressBar("舱室压力", 65),
                new StatusProgressBar("基板温度", 80),
                new StatusProgressBar("氧含量", 55),
                new StatusProgressBar("过滤器氧含量", 90),
                new StatusProgressBar("风速", 70),
            };

            // 时间
            CurrentTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            _timer = new DispatcherTimer();
            _timer.Interval = TimeSpan.FromSeconds(1);
            _timer.Tick += (s, e) => { CurrentTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); };
            _timer.Start();

            // 命令
            ShowMonitorSettingCommand = new RelayCommand(_ =>
            {
                var win = new MonitorSettingWindow();
                win.DataContext = this;
                win.Owner = Application.Current.MainWindow;
                win.ShowDialog();
            });

            ConnectMonitorCommand = new RelayCommand(_ =>
            {
                /* 连接监控IP逻辑 */
            });
            UploadFileCommand = new RelayCommand(_ => UploadModel());
            DeleteFileCommand = new RelayCommand(_ => DeleteModel());

            ShowMenuCommand = new RelayCommand(param =>
            {
                if (param is TopMenuButton btnClicked)
                {
                    SelectedTopMenuIndex = TopMenuButtons.IndexOf(btnClicked);
                    // 切换页面
                    if (btnClicked.Name == "首页")
                        CurrentPage = new HomePage { DataContext = this };
                    else if (btnClicked.Name == "手动模式")
                        CurrentPage = new ProductionPage { DataContext = new ProductionPageViewModel() };
                    // 你可以继续添加其他页面
                }
            });

            LogoutCommand = new RelayCommand(_ => Logout());

            // 默认显示首页
            CurrentPage = new HomePage { DataContext = this };
        }

        private void Logout()
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                var loginWin = new LoginWindow();
                loginWin.Show();
                foreach (Window win in Application.Current.Windows)
                {
                    if (win is MainWindow)
                    {
                        win.Close();
                        break;
                    }
                }
            });
        }

        private void UploadModel()
        {
            var dlg = new OpenFileDialog
            {
                Filter = "STL文件 (*.stl)|*.stl|OBJ文件 (*.obj)|*.obj|所有文件 (*.*)|*.*"
            };
            if (dlg.ShowDialog() == true)
            {
                try
                {
                    Model3D model = null;
                    if (dlg.FileName.ToLower().EndsWith(".stl"))
                    {
                        var reader = new StLReader();
                        model = reader.Read(dlg.FileName);
                    }
                    else if (dlg.FileName.ToLower().EndsWith(".obj"))
                    {
                        var reader = new ObjReader();
                        var modelGroup = reader.Read(dlg.FileName);
                        model = modelGroup;
                    }

                    if (model != null)
                    {
                        Model3D = model;
                        IsModelLoaded = true;
                        _currentModelFilePath = dlg.FileName;
                    }
                    else
                    {
                        MessageBox.Show("模型加载失败！");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("模型加载出错：" + ex.Message);
                }
            }
        }

        private void DeleteModel()
        {
            Model3D = null;
            IsModelLoaded = false;
            _currentModelFilePath = null;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged([CallerMemberName] string name = null)
            => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }


    public class TopMenuButton : INotifyPropertyChanged
    {
        public string Name { get; set; }
        public string Icon { get; set; }

        public TopMenuButton(string name)
        {
            Name = name;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged([CallerMemberName] string name = null)
            => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }

    // 进度条类
    public class StatusProgressBar : INotifyPropertyChanged
    {
        public string Name { get; }
        private int _value;

        public int Value
        {
            get => _value;
            set
            {
                _value = value;
                OnPropertyChanged();
            }
        }

        public StatusProgressBar(string name, int value)
        {
            Name = name;
            Value = value;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged([CallerMemberName] string name = null)
            => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }

    // 简单RelayCommand实现
    public class RelayCommand : ICommand
    {
        private readonly Action<object> _execute;
        private readonly Predicate<object> _canExecute;

        public RelayCommand(Action<object> execute, Predicate<object> canExecute = null)
        {
            _execute = execute;
            _canExecute = canExecute;
        }

        public bool CanExecute(object parameter) => _canExecute == null || _canExecute(parameter);
        public void Execute(object parameter) => _execute(parameter);

        public event EventHandler CanExecuteChanged
        {
            add { }
            remove { }
        }
    }
}